package com.shop.loan.proxy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.NumberUtil;
import com.shop.loan.mapper.UserByMybatisMapper;
import com.shop.loan.model.entity.UserByMybatis;
import com.shop.loan.model.view.LoanOrderByChannel;
import com.shop.loan.util.LoanOrderUtil;
import com.shop.loan.util.Util;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import xyz.erupt.annotation.fun.DataProxy;
import xyz.erupt.annotation.query.Condition;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class LoanOrderByChannelProxy implements DataProxy<LoanOrderByChannel> {

    @Resource
    LoanOrderUtil loanOrderUtil;

    @Resource
    UserByMybatisMapper userByMybatisMapper;

    @Override
    public String beforeFetch(List<Condition> conditions) {
        conditions.removeIf(condition -> "userName".trim().equals(condition.getKey()));

        String sql = "";
        List<Long> userIds = loanOrderUtil.getUserIdBySearch();
        String userIdStr = null;
        if (userIds != null && userIds.size() > 0) {
            userIdStr = org.apache.commons.lang3.StringUtils.join(userIds, ",");
        }
        if (StringUtils.hasLength(userIdStr)) {
            sql = "LoanOrderByChannel.user.id in (" + userIdStr + ")";
        }
        if (StringUtils.hasLength(sql)) {
            return sql + " and (LoanOrderByChannel.channelStatistics = null or LoanOrderByChannel.channelStatistics = true)";
        }
        return " (LoanOrderByChannel.channelStatistics = null or LoanOrderByChannel.channelStatistics = true)";
    }

    @Override
    public void afterFetch(Collection<Map<String, Object>> list) {
        dataOp(list);
    }


    public void dataOp(Collection<Map<String, Object>> list) {
        for (Map map : list) {
            Long id = Long.valueOf(map.get("id").toString());
            if (map.get("createTime") != null) {
                String createTime = map.get("createTime").toString();
                if (createTime != null && NumberUtil.isLong(createTime)) {
                    map.put("createTime", DateUtil.formatDateTime(DateUtil.date(Long.parseLong(createTime))));
                }
            }

            //用户手机号码
            UserByMybatis user = userByMybatisMapper.selectByOrderId(id);
            if (user != null) {
                map.put("user_name", Util.desensitizedName(user.getCardName()) + "【" + DesensitizedUtil.mobilePhone(user.getMobile()) + "】");
            }
        }
    }


}
